import {
  ProForm,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import { Form, message, Upload } from 'antd';
import { getToken, getUserData, } from '../../../utils/const.ts';
import { PlusOutlined, } from '@ant-design/icons';
import { request } from '../../../utils/request.ts';
import { useEffect, useState } from 'react';

const Profile = () => {
  const [form] = Form.useForm();
  const [userStr, setUserStr] = useState({});
  const uploadProps = {
    headers: {
      token: getToken(),
    },
    maxCount: 1,
  }

  useEffect(() => {
    try {
      const userStr = getUserData();
      if (userStr) {
        const user = JSON.parse(userStr);
        setUserStr(user);
        const initial = {
          ...user,
          pic: user?.pic
            ? [{
              uid: '-1',
              name: '头像.png',
              status: 'done',
              url: userStr?.pic,
            }]
            : [],
        };
        form.setFieldsValue(initial);
      }
    } catch (e) { 
      console.log(e);
    }
  }, []);

  return (
    <div style={{ width: '100%', background: '#fff' }}>
      <ProForm
        title={"更新个人信息"}
        form={form}
        autoFocusFirstInput
        style={{ width: 500, margin: '0 auto', padding: '20px 0', }}
        layout="horizontal" // 关键点
        labelCol={{ span: 6 }} // label 占 6/24
        wrapperCol={{ span: 18 }} // 输入框占 18/24
        onFinish={async (values) => {
          const { pic, ...other } = values;
          try {
            const res = await request('/api/user/update', {
              method: 'POST',
              data: {
                ...other,
                pic: pic && pic[0]?.response?.data ? pic[0].response.data : userStr?.pic,
              },
            });
            if (res.data) {
              message.success('提交成功');
            } else {
              message.error(res.msg);
            }
          } catch (error) {
            console.error('Failed to submit data:', error);
          }
          return true;
        }}
        submitter={{
          render: (props, doms) => (
            <div style={{ textAlign: 'center', gap: 16, display: 'flex', justifyContent: 'center', }}>{doms}</div>
          ),
        }}
      >
        <ProFormText name="email" label="邮箱" rules={[{ required: true, }]} />
        <ProFormText name="password" label="密码" valueType="password" rules={[{ required: true, }]} />
        <ProFormText name="address" label="单位" rules={[{ required: true, }]} />
        <ProFormText name="idcard" label="身份证号码" rules={[{ required: true, }]} />
        <ProFormText name="name" label="姓名" rules={[{ required: true, }]} />
        <ProFormDatePicker name="birthday" label="生日" rules={[{ required: true, }]} />
        <Form.Item
          label="头像"
          name="pic"
          valuePropName="fileList"
          getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList}
          rules={[
            { required: true, message: '请上传头像' },
          ]}
        >
          <Upload name="file" action="/api/uploadFile" {...uploadProps} listType="picture-card">
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>Upload</div>
            </div>
          </Upload>
        </Form.Item>
      </ProForm >
    </div>
  );
};
export default Profile;